<template>
  <div id="batchProcessDiv">
    <Breadcrumb content="阴性结果批量审核" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <span class="padding-right-xs">报告单元:</span>
              <SelectWorkGroupBac :url="'/api/rptGroup/findRptGroupList'" :inputWidth="'100%'" :businessType="'20'" @getSelectedId="getSelectedId" />
              <span class="margin-lr-xs text-Bold text-shadow">条码号:</span>
              <vxe-input ref="reqNoInputRef" v-model="searchform.reqNo" clearable @keyup="specInputKeyUp" :disabled="isspdisable"></vxe-input>
              <vxe-button type="text" class="button-blue margin-left-xs" @click="chongzhiFun">重置</vxe-button>
              <vxe-button type="text" class="button-blue margin-left-xs" @click="batchSaveBacResult" :loading="loading">保存</vxe-button>
              <vxe-button type="text" class="button-blue margin-left-xs" @click="batchChkBacResult" :loading="cloading">审核</vxe-button>
              <vxe-button type="text" class="button-red margin-left-xs" @click="batchUnChkBacResult" :loading="uloading">消审</vxe-button>

            </template>
          </vxe-toolbar>
          <div class="tableBody" >
            <vxe-table ref="specSignDetailTable" v-loading="loading" border class="mytable-scrollbar" height="auto" :data="labMaininfoList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" @current-change="mininfoRowClick" :cell-style="cellClassName" resizable show-overflow>
              <vxe-column type="seq" title="序号" width="30"></vxe-column>
              <vxe-column field="isChk" width="20" align="center" fixed="left" class-name="flag-cell">
                <template #header>
                  <span style="font-weight: 150; font-size: 8px">审</span>
                </template>
                <template #default="{ row }">
                  <i v-if="row.isChk === 1" class="el-icon-s-check">
                    <span style="color: #fff">初</span>
                  </i>
                  <i v-else-if="row.isChk === 2 || row.isChk === 1" class="el-icon-finished">
                    <el-icon>
                      <SuccessFilled />
                    </el-icon>
                  </i>
                </template>
              </vxe-column>
              <vxe-column field="reqNo" title="条码号" width="100px"></vxe-column>
              <vxe-column field="sampleNo" title="标本号" width="100px"></vxe-column>
              <vxe-column field="patNa" title="姓名" width="100px"></vxe-column>
              <vxe-column field="age" title="年龄" width="100px"></vxe-column>
              <vxe-column field="patNo" title="病历号" width="100px"></vxe-column>
              <vxe-column field="reqPurpose" title="申请目的"></vxe-column>
              <vxe-column field="workFlowNa" title="流程方案" width="150px"></vxe-column>

            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <Splitpanes horizontal class="horizontalLine">
            <Pane size="50">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="toolbartitle">默认结果</div>
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-table ref="staRoleTableRef" class="mytable-scrollbar staRoleTableClazz" border="inner" align="center" height="auto" :data="stlMaininfo.addbacTestResults" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                  <vxe-column field="germNa" title="默认结果"></vxe-column>

                </vxe-table>
              </div>
            </Pane>
            <Pane size="50">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="toolbartitle">已有结果</div>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBacRptReuslt"></vxe-button>
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-table ref="bacTestResultRef" :data="stlMaininfo.bacTestResultList" class="mytable-scrollbar staRoleTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                  <vxe-column type="checkbox" width="30"></vxe-column>

                  <vxe-column field="isolateNum" title="编号"></vxe-column>
                  <vxe-column field="germNa" title="鉴定结果"> </vxe-column>
                  <vxe-column field="resiPhenNa" title="耐性表型"> </vxe-column>

                </vxe-table>
              </div>
            </Pane>

          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
    <!-- 审核密码授权 -->
    <ChkAuthComp ref="ChkAuthCompRef" @AuthSuccess="chkConfirm" />
    <!-- 授权验证组件 -->
    <AuthValidateComp ref="AuthValidateCompRef" @unChkConfirm="unChkConfirm" />
  </div>
</template>
<script lang="ts" setup>
/**引入组件区 ==========*/
import Breadcrumb from '@/components/Breadcrumb.vue'; /**面包屑*/
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { isEmpty } from 'lodash';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import SelectWorkGroupBac from '@/views/lab_sys/lab_bus/components/SelectWorkGroupBac.vue'; //报告单元引入下拉组件
import { VXETable } from 'vxe-table';
import { AppStore } from '@/stores/store';
import ChkAuthComp from '@/components/ChkAuthComp.vue';
import { IsEmpty, formatDateTime, sortByField } from '@/utils/common.ts';
import { getOptionValueByCodeRptGroupOption, getOptionValueByCodeGlobalOption } from '@/utils/SysOptionsHelper';
import AuthValidateComp from '@/components/AuthValidateComp.vue'; //AuthValidateComp

const ChkAuthCompRef = ref(null); /**审核确认弹窗 */
let AuthValidateCompRef = ref(null); //授权验证弹窗对象

const storeObj = AppStore();

/**全局变量定义区 ==========*/
let { proxy }: any = getCurrentInstance();
let isspdisable = ref(false);
let loading = ref(false);
let cloading = ref(false);
let uloading = ref(false);
let searchform = reactive({
  reqNo: '',
  rptGroup: ''
});
/**报告单元选中事件改变 */
function getSelectedId(e) {
  searchform.rptGroup = e.value;
}

function specInputKeyUp(e) {
  if (e.$event.code === 'Enter' || e.$event.code === 'NumpadEnter') {
    if (isEmpty(searchform.reqNo) || isEmpty(searchform.reqNo.trim())) {
      VxeMessage('条码号不可为空', VxeNotifyType.error);
    } else {
      isspdisable.value = true;
      try {
        const url = '/api/bac/flowDefResult/getBacMaininfoByReqNo';
        proxy.$http
          .get(url, { params: { reqNo: searchform.reqNo, rptGroup: searchform.rptGroup } })
          .then(async (res: any) => {
            if (res.status.code == 400) {
              await VXETable.modal.alert(res.status.msg);
              const time = setTimeout(() => {
                clearSpecCodeInput();
                clearTimeout(time);
              }, 200);
            } else {
              const cnt = labMaininfoList.findIndex((p) => p.reqNo == searchform.reqNo);
              if (cnt <= -1) {
                const index = handleAdd(searchform.reqNo);
                let currMaininfo = res.data.labMaininfo;
                currMaininfo.addbacTestResults = res.data.addbacTestResults;
                currMaininfo.bacTestResultList = res.data.bacTestResultList;

                Object.assign(labMaininfoList[index], currMaininfo);
                mininfoRowClick({ row: labMaininfoList[index] });
              }
              const time = setTimeout(() => {
                clearSpecCodeInput();
                clearTimeout(time);
              }, 200);
            }
          })
          .catch((err: any) => {
            proxy.$alert(err, '提示');
          });
      } catch (err) {}
    }
  }
}
let labMaininfoList = reactive([]); //列表

function chongzhiFun() {
  labMaininfoList.length = 0;
  stlMaininfo.value = {};
}

function batchSaveBacResult() {
  if (labMaininfoList.length > 0) {
    let saveBacRptReusltList = [];
    for (const mf of labMaininfoList) {
      saveBacRptReusltList.push(...mf.addbacTestResults);
    }
    if (saveBacRptReusltList.length > 0) {
      const data = { bacTestResultList: saveBacRptReusltList };
      const url = '/api/bac/flowDefResult/batchSaveBacTestResult';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          if (res.status.code == 200) {
            //保存之后 清空默认结果，再已有结果中添加已有结果
            for (const mf of labMaininfoList) {
              mf.addbacTestResults = [];
              let addTestReulstList = res.data;
              const temp = addTestReulstList.filter((data) => data.sampleNo == mf.sampleNo);
              mf.bacTestResultList.push(...temp);
            }
          }
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('无默结果', VxeNotifyType.info);
    }
  } else {
    VxeMessage('无上机记录', VxeNotifyType.info);
  }
}

function batchChkBacResult() {
  if (storeObj.chkDoctorObj) {
    const curDateTime = new Date().valueOf();
    if (Number(curDateTime) > Number(storeObj.chkDoctorObj.expressin)) {
      if (ChkAuthCompRef.value) {
        ChkAuthCompRef.value?.initPage(true, '审核');
      }
      storeObj.clearChkDoctorObj();
      return;
    }
    let resData = { edtType: 1, codeRange: '', action: '2' };
    batchChkBacResultMM(resData);
    return;
  }
  if (ChkAuthCompRef.value) {
    ChkAuthCompRef.value?.initPage(true, '审核');
  }
}

/**审核确认 */
function chkConfirm(e: any) {
  batchChkBacResultMM(e);
}
function batchChkBacResultMM(e) {
  let acterCode = storeObj && storeObj.chkDoctorObj && !isEmpty(storeObj.chkDoctorObj.code) ? storeObj.chkDoctorObj.code : '';
  let acterNa = storeObj && storeObj.chkDoctorObj && !isEmpty(storeObj.chkDoctorObj.name) ? storeObj.chkDoctorObj.name : '';

  if (labMaininfoList.length > 0) {
    let chkMainList = labMaininfoList.filter((p) => p.isChk < 2);

    let saveBacRptReusltList = [];
    let uptMainInfoTextChkDoctorDtoList = [];
    for (const mf of chkMainList) {
      //saveBacRptReusltList.push(...mf.addbacTestResults);
      uptMainInfoTextChkDoctorDtoList.push({ rptGroup: mf.rptGroup, sampleda: mf.sampleda, id: mf.id, edtType: e.edtType, codeRange: e.codeRange, action: '2', acterCode: acterCode, acterNa: acterNa });
    }
    if (uptMainInfoTextChkDoctorDtoList.length > 0) {
      cloading.value = true;
      const data = { bacTestResultList: saveBacRptReusltList, uptMainInfoTextChkDoctorDtoList: uptMainInfoTextChkDoctorDtoList };
      const url = '/api/bac/flowDefResult/batchChkBacTestResult';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          if (res.status.code == 200) {
            let addTestReulstList = res.data.addTestReulstList;
            let upmainList = res.data.maininfoList;
            //保存之后 清空默认结果，再已有结果中添加已有结果
            for (const mf of labMaininfoList) {
              mf.addbacTestResults = [];
              const temp = addTestReulstList.filter((data) => data.sampleNo == mf.sampleNo);
              mf.bacTestResultList.push(...temp);
              const tempm = upmainList.find((data) => data.id == mf.id);
              if (!isEmpty(tempm)) {
                mf.isChk = tempm.isChk;
              }
            }
          }
          VxeMessage(res.status.msg, VxeNotifyType.success);
          cloading.value = false;
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('无审核数据', VxeNotifyType.info);
    }
  } else {
    VxeMessage('无上机记录', VxeNotifyType.info);
  }
}

/**取消审核验证成功返回 */
function unChkConfirm(e: any) {
  batchUnChkBacResultMM(e);
}
function batchUnChkBacResult() {
  if (labMaininfoList.length > 0) {
    let unchkMainList = labMaininfoList.filter((p) => p.isChk == 2);
    if (unchkMainList.length > 0) {
      /**消审操作人需再登录 xsczrxyzdl */
      const a = getOptionValueByCodeGlobalOption('shstcwjzsbjm'); /**消审操作人需再登录 xsczrxyzdl*/
      if (a && (a === '1' || a === 1)) {
        if (AuthValidateCompRef.value) {
          AuthValidateCompRef.value?.initPage(true, '取消审核验证');
          return;
        }
      }

      batchUnChkBacResultMM(null);
    } else {
      VxeMessage('无消审数据', VxeNotifyType.info);
    }
  } else {
    VxeMessage('无上机记录', VxeNotifyType.info);
  }
}

function batchUnChkBacResultMM(authUser: any) {
  let unchkMainList = labMaininfoList.filter((p) => p.isChk == 2);
  if (unchkMainList.length > 0) {
    if (authUser) {
      for (let ar of unchkMainList) {
        ar.unChkDoctor = IsEmpty(authUser.code) ? '' : authUser.code;
        ar.unChkDoctorNa = IsEmpty(authUser.name) ? '' : authUser.name;
      }
    }
    uloading.value = true;
    const data = { labMaininfoList: unchkMainList };

    const url = '/api/bac/flowDefResult/batchUnChkBacTestResult';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        //审核返回
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data) {
          let unchkmainList = res.data;
          for (const mf of labMaininfoList) {
            const tempm = unchkmainList.find((data) => data.id == mf.id);
            if (!isEmpty(tempm)) {
              mf.isChk = tempm.isChk;
            }
          }
        } else if (res && res.status && !IsEmpty(res.status.code) && res.status.code !== 1) {
          VxeMessage(res.status.msg ? res.status.msg : '取消审核检验失败,请联系管理员', VxeNotifyType.error);
        } else if (res && res.status && !IsEmpty(res.status) && res.status === 500) {
          VxeMessage(res.message ? res.message : '取消审核检验失败,请联系管理员', VxeNotifyType.error);
        }
        uloading.value = false;
      })
      .catch((err: any) => {
        VxeMessage('取消检验失败', VxeNotifyType.error);
      });
  }
}

//新增性状
function handleAdd(specCode) {
  const newRow = {
    id: null,
    reqNo: specCode
  };

  labMaininfoList.unshift(newRow);
  // const $table = proxy.$refs.specSignDetailTable as any;
  // $table.reloadData(labMaininfoList);

  // $table.setCurrentRow(newRow);

  return 0; //specSignDetailList.length - 1;
}
let stlMaininfo: any = ref({});
function mininfoRowClick({ row }: any) {
  (proxy.$refs.specSignDetailTable as any).setCurrentRow(row);
  stlMaininfo.value = row;
}

//  删除
function deleteBacRptReuslt() {
  const sltMaterialItems = (proxy.$refs.bacTestResultRef as any).getCheckboxRecords();
  if (!(sltMaterialItems.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { bacTestResultList: sltMaterialItems };
        const url = '/api/bac/flowDefResult/batchDeleteBacTestResult';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            if (res.status.code == 200) {
              // 删除的新增的空白数据 不走接口
              let $Xtable = proxy.$refs.bacTestResultRef;
              if ($Xtable) {
                for (const removeRow of sltMaterialItems) {
                  const iindex = stlMaininfo.value.bacTestResultList.findIndex((item) => item.id == removeRow.id);
                  stlMaininfo.value.bacTestResultList.splice(iindex, 1);
                }
              }
            }
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 条码号输入框清空，并获取焦点
function clearSpecCodeInput() {
  isspdisable.value = false;
  searchform.reqNo = '';
  setTimeout(() => {
    (proxy.$refs.reqNoInputRef as any).focus();
  }, 20);
}

function cellClassName({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  let patTypeColor = '';
  if (column && !IsEmpty(column.fixed)) {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      if (row && row.patType === '1') {
        //门诊
        const b = getOptionValueByCodeGlobalOption('mzpattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else if (row && row.patType === '2') {
        //急诊
        const b = getOptionValueByCodeGlobalOption('jzpattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else if (row && row.patType === '3') {
        //住院
        const b = getOptionValueByCodeGlobalOption('zypattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else if (row && row.patType === '4') {
        //体检
        const b = getOptionValueByCodeGlobalOption('tjpattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else {
        //其他
        if (!IsEmpty(row.patType)) {
          const b = getOptionValueByCodeGlobalOption('qtpattypecolor');
          if (!IsEmpty(b)) {
            patTypeColor = b;
          }
        }
      }
    }
  }
  if (column.property === 'isUrgent') {
    if (row.isUrgent === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isurgentcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff', padding: '0', margin: '0' };
        }
      }
      return { background: '#FF0000', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isChk') {
    if (row.isChk === 2) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('ischkcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#008000', color: '#fff' };
    } else if (row.isChk === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('ischkcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#00FF00', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isAlarm') {
    if (row.isAlarm === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isalarmcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#FF9900', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isAutoPrint') {
    if (row.isAutoPrint === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isautoprintcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#800080', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isPrint') {
    if (row.isPrint === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isprintcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#000080', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
}
</script>
<style lang="scss" scoped>
#batchProcessDiv {
  width: 100%;
  height: 100%;
  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .compute-button {
        background-color: #89d7fc;
      }
    }
    // 中间table表格
    .tableBody {
      height: calc(100% - 40px);
    }
    .tableBox {
      height: calc(100% - 40px);
    }
  }
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
}
</style>